package yqiniu

import (
	"time"

	"gitee.com/liuyongchina/go-library/config"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"github.com/spf13/cast"
)

var TokenData *AceessToken

type AceessToken struct {
	aceessToken string
	expireTime  int64
}

//GetSimpleToken 简单上传的凭证
func GetSimpleToken(bucketName string) string {
	if TokenData != nil {
		if time.Now().Unix() < TokenData.expireTime {
			return TokenData.aceessToken
		}
	}
	qiniuConfig := config.NewQiniu().GetConfig()
	bucket := qiniuConfig.Bucket[bucketName].BucketName
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	putPolicy.Expires = 7200
	mac := qbox.NewMac(qiniuConfig.Ak, qiniuConfig.Sk)
	upToken := putPolicy.UploadToken(mac)
	expireTime := cast.ToInt64(time.Now().Unix() + 7200 - 300)
	TokenData = &AceessToken{aceessToken: upToken, expireTime: expireTime}
	return upToken
}
